package com.example.demo.study.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

public class JwtUtil {
    public static final Long JWT_TTL= 60*60*1000L;
    public static final String JWT_KEY="lyangbo";

    public static String getUUID(){
        String token = UUID.randomUUID().toString().replaceAll("-","");
        return token;
    }

    /**
     * 生成 Jwt
     * @param subject
     * @return
     */
    public static String createJWT(String subject ){
        JwtBuilder builder = getJwtBuilder(subject,null,getUUID());
        return builder.compact();
    }

    /**
     * 生成 Jwt
     * @param subject
     * @param ttlMillis
     * @return
     */
    public static String createJWT(String subject ,Long ttlMillis){
        JwtBuilder builder = getJwtBuilder(subject,ttlMillis,getUUID());
        return builder.compact();
    }

    /**
     * 创建 token
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     */
    public static String createJWT(String id, String subject, Long ttlMillis){
        JwtBuilder builder = getJwtBuilder(subject,ttlMillis,id);// 设置过期时间
        return builder.compact();
    }

    public static JwtBuilder getJwtBuilder(String subject, Long ttiMillis,String uuid){
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if(ttiMillis == null) {
            ttiMillis=JwtUtil.JWT_TTL;
        }

        long expMillis = nowMillis + ttiMillis;
        Date expDate = new Date(expMillis);
        return Jwts.builder()
                .setId(uuid)            //唯一的ID
                .setSubject(subject)    // 主题可以是JSON数据
                .setIssuer("sg")        // 签发者
                .setIssuedAt(now)       // 签发时间
                .signWith(signatureAlgorithm,secretKey) //使用HS256对称加密算法签名，第二个参数为秘钥
                .setExpiration(expDate);


    }


    public static void main(String[] args) throws Exception {
        String token = "eyJhbGcioiJIUZI1NiJ9.eyJgdGkioiJjMWM2ZDVhzi1mNjV1LTOOMDAtYjcxMiZYWEWOGIyOTIWYjQiLCJzdWIi0iJzzyIsImlzcyI6InNnIiwiaWFOIjoxNjM4MTA2NZEyLCJ1eHAiOjE2MzgxMTAZMTJ9 ,JVsSbkp94wuczb4QryobAke3ysBDIL5ou8fwsbt_ebg";
        Claims claims = parseJWT(token);
        System.out.println(claims);
    }

    /**
     * 生成加密后的秘钥 SecretKey
     * @return
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AEs");
        return key;
    }

    /**
     * 解析
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws Exception{
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

}
